<script setup>
import {onMounted, reactive, ref} from "vue";
import {
  addAnnouncementService,
  deleteAnnouncementService,
  deleteAnnouncementsService,
  exportAnnouncementDataService,
  getUserPageService,
  updateAnnouncementService,
  updateAnnouncementStatusService,
  updateAnnouncementTopService
} from '../api/announcement.js'
import {ElMessage, ElMessageBox} from "element-plus";

const title = ref('')
const content = ref('')
const pageNum = ref(1)
const pageSize = ref(5)
const tableData = ref([])
const total = ref(0)
const dialogVisibleContent = ref(false);
const dialogVisibleAdd = ref(false);
const currentContent = ref('');
const selectedRows = ref([])
const dialogTitle = ref('新增公告')
const AnnouncementForm = reactive({
  id: null,
  title: '',
  content: '',
  isTop: 0,
  status: 0,
  publishTime: null
})
const user = JSON.parse(localStorage.getItem('user'))
const token = user?.token
const rules = {
  title: [
    {required: true, message: '标题不能为空', trigger: 'blur'}
  ],
  content: [
    {required: true, message: '内容不能为空', trigger: 'blur'}
  ],
  publishTime: [
    {required: true, message: '发布时间不能为空', trigger: 'blur'}
  ]
};
const formRef = ref();

// 刷新
const refresh = async () => {
  title.value = ''
  content.value = ''
  await AnnouncementList()
}

// 公告列表
const AnnouncementList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    title: title.value,
    content: content.value
  }
  const res = await getUserPageService(params)

  if (res.data.code === '200') {
    tableData.value = res.data.data.list
    total.value = res.data.data.total
  } else {
    ElMessage.error(res.data.message)
  }
}

// 页面加载时执行
onMounted(() => {
  AnnouncementList()
})

// 显示弹窗（查看）
const showContentDialog = (row) => {
  dialogTitle.value = '公告内容'
  currentContent.value = row.content;
  dialogVisibleContent.value = true;
};

// 显示弹窗（新增）
const showAddDialog = () => {
  dialogTitle.value = '新增公告'
  AnnouncementForm.title = ''
  AnnouncementForm.content = ''
  AnnouncementForm.isTop = 0
  AnnouncementForm.status = 0
  AnnouncementForm.publishTime = null
  dialogVisibleAdd.value = true
}

// 显示弹窗（修改）
const showEditDialog = (row) => {
  dialogTitle.value = '修改公告'
  AnnouncementForm.id = row.id
  AnnouncementForm.title = row.title
  AnnouncementForm.content = row.content
  AnnouncementForm.isTop = row.isTop
  AnnouncementForm.status = row.status
  AnnouncementForm.publishTime = row.publishTime
  dialogVisibleAdd.value = true
}

// 修改公告
const handleUpdateAnnouncement = async () => {
  const res = await updateAnnouncementService(AnnouncementForm);
  if (res.data.code === '200') {
    ElMessage.success('修改成功');
    dialogVisibleAdd.value = false;
    await AnnouncementList();
  } else {
    ElMessage.error(res.data.message);
  }
}

// 保存公告
const handleSave = async () => {
  const valid = await formRef.value.validate().catch(() => false);
  if (valid) {
    if (AnnouncementForm.id) {
      await handleUpdateAnnouncement(AnnouncementForm);
    } else {
      await handleAddAnnouncement(AnnouncementForm);
    }
  } else {
    ElMessage.error('请填写完整信息');
  }

}

// 分页 - pageSize 改变时
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  AnnouncementList();
};

// 分页 - pageNum 改变时
const handleCurrentChange = (newPage) => {
  pageNum.value = newPage;
  AnnouncementList();
};

// 表格行数据
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 批量删除
const handleDeleteBatch = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的公告");
    return;
  }

  const ids = selectedRows.value.map(item => item.id)

  ElMessageBox.confirm(
      '当前操作将永久删除选中的公告，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteAnnouncementsService(ids);
    if (res.data.code === "200") {
      ElMessage.success("删除成功");
      await AnnouncementList();
    } else {
      ElMessage.error(res.data.message);
    }
  }).catch(() => {
    ElMessage.info('取消删除');
  });
}

// 新增公告
const handleAddAnnouncement = async () => {
  const res = await addAnnouncementService(AnnouncementForm);

  if (res.data.code === '200') {
    ElMessage.success('新增成功');
    dialogVisibleAdd.value = false;
    await AnnouncementList();
  } else {
    ElMessage.error(res.data.message);
  }
};

// 修改状态
const handleStatusChange = async (value, row) => {
  await updateAnnouncementStatusService({id: row.id, status: value})
}

// 修改置顶
const handleIsTopChange = async (value, row) => {
  await updateAnnouncementTopService({id: row.id, isTop: value})
}

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

// 删除公告
const handleDelete = async (id) => {
  ElMessageBox.confirm(
      '当前操作将永久删除当前公告，是否继续?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
  ).then(async () => {
    const res = await deleteAnnouncementService(id)
    if (res.data.code === "200") {
      ElMessage.success("删除成功")
      await AnnouncementList()
    } else {
      ElMessage.error(res.data.message)
    }
  }).catch(() => {
    ElMessage.info('取消删除')
  })
}

// 导出数据
const handleExport = async () => {
  try {
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning("当前无数据可导出");
      return;
    }
    await exportAnnouncementDataService({
      title: title.value ? title.value : null,
      content: content.value ? content.value : null,
      ids: selectedRows.value.map(item => item.id) ? selectedRows.value.map(item => item.id) : null
    })
    ElMessage.success("导出成功")
  } catch (error) {
    ElMessage.error("导出失败")
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isValidFormat = /\.(xlsx|xls)$/.test(file.name);
  if (!isValidFormat) {
    ElMessage.error("只能上传 Excel 文件");
    return false;
  }
  return true;
};

// 上传成功
const handleSuccess = (response) => {
  if (response.code === "200") {
    ElMessage.success("导入成功" || response.message);
    AnnouncementList();
  } else {
    ElMessage.error(response.message);
  }
};

</script>

<template>
  <el-card>
    <!-- 搜索区域 -->
    <div>
      <el-input v-model="title" clearable style="width: 240px" placeholder="请输入标题"/>
      <el-input v-model="content" clearable style="width: 240px; margin: 0 20px" placeholder="请输入内容"/>
      <el-button type="primary" style="margin-left: 20px" icon="Search" @click="AnnouncementList">查询</el-button>
      <el-button type="warning" icon="refresh" @click="refresh">重置</el-button>
    </div>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="primary" icon="DocumentAdd" @click="showAddDialog">新增公告</el-button>
      <el-button type="danger" style="margin-left: 0" icon="Delete" @click="handleDeleteBatch">批量删除</el-button>
      <el-upload
          ref="uploadRef"
          :headers="{ Authorization: token }"
          action="http://127.0.0.1:9090/api/announcement/import"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload">
        <el-button type="success" icon="Download">导入数据</el-button>
      </el-upload>
      <el-button type="info" icon="Upload" @click="handleExport">导出数据</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="tableData" @selection-change="handleSelectionChange" border
                :row-style="() => ({ height : '58px'})" style="width: 100%;">
        <el-table-column type="selection" align="center" width="55"/>
        <el-table-column prop="title" align="center" label="标题"/>
        <el-table-column prop="content" align="center" label="内容">
          <template #default="scope">
            <el-button type="info" icon="Document" @click="showContentDialog(scope.row)">显示内容</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status"
                       :active-value="0"
                       :inactive-value="1"
                       style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                       @change="(value) => handleStatusChange(value, scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="发布时间">
          <template #default="scope">
            <el-text type="info">{{ formatDate(scope.row.publishTime) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" @click="showEditDialog(scope.row)" icon="Edit">修改</el-button>
            <el-button type="danger" icon="Delete" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="page">
      <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="prev, pager, next, jumper, sizes"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </el-card>

  <el-dialog v-model="dialogVisibleContent" :title="dialogTitle" align-center width="500" destroy-on-close>
    <div style="padding: 0 20px; white-space: pre-wrap;">
      {{ currentContent }}
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisibleContent = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="dialogVisibleAdd" :title="dialogTitle" align-center width="500" destroy-on-close>
    <el-form :model="AnnouncementForm" :rules="rules" ref="formRef" label-width="80px"
             style="padding: 0 50px 0 0">
      <el-form-item label="标题" prop="title">
        <el-input v-model="AnnouncementForm.title" placeholder="请输入标题"/>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
            v-model="AnnouncementForm.content"
            placeholder="请输入内容"
            :rows="6"
            type="textarea"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
            v-model="AnnouncementForm.status"
            :active-value="0"
            :inactive-value="1"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取消</el-button>
        <el-button type="primary" @click="handleSave">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.button {
  margin-top: 20px;
}

.table {
  margin-top: 20px;
}

.page {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.button-container {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

:deep() .el-form-item {
  margin-top: 25px;
}
</style>